package com.tobie.userservice.controller;

import com.common.uaa.entity.UserEntity;
import com.common.utils.ResultVo;
import com.tobie.userservice.pojo.dto.UserDto;
import com.tobie.userservice.pojo.vo.UserVo;
import com.tobie.userservice.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author Tobieance
 * @description
 * @date 2023-11-16 14:51
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    IUserService userService;

    @PostMapping("/register")
    public ResultVo<String> register(@Valid @RequestBody UserDto userDto, BindingResult bindingResult) {
        //判断校验结果
        if (bindingResult.hasErrors()) {
            //打印校验错误数量
            log.info("校验错误数量:" + bindingResult.getErrorCount());
            val fieldErrors = bindingResult.getFieldErrors();
            //打印校验错误信息
            log.info("校验错误信息:");
            for (val fieldError : fieldErrors) {
                log.info(fieldError.toString());
            }
            return ResultVo.fail(fieldErrors.toString());
        } else {
            userService.registerUser(userDto);
        }
        return ResultVo.success("注册成功");
    }

    @GetMapping("/info")
    @PreAuthorize("hasAnyAuthority('user','admin')")//设置允许访问的权限
    public ResultVo<UserVo> getInfo() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        UserEntity userEntity = (UserEntity) authentication.getPrincipal();
        UserVo userVo=new UserVo();
        BeanUtils.copyProperties(userEntity,userVo);
        log.info(userVo.toString());
        return ResultVo.success(userVo);
    }
}
